var do_App = sm("do_App");
var do_Page = sm("do_Page");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var deviceone = require("deviceone");
var qqHttp = require("helper/http");
var httpSilence = require("helper/httpSilence");
var imgTool = require("helper/picture");
var helperOpen = require("helper/open");
var device = require("helper/device");

var userLoginHelper = require("helper/userLogin");
//定义一个DateTimePicker对象
var do_DateTimePicker = sm("do_DateTimePicker")

var activityUrl = require("url/activity");
var activityCreateUrl = activityUrl.url.base.create;

// UI
var headerAout = ui("headerAout");
var aLayoutRoot = ui("aLayoutRoot");
var layoutForm = ui("layoutForm");
var root = ui("$");
//定义时间
var myDate=new Date();
var date0 = myDate.getTime();

// 加载头部
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
// andriod返回键
do_Page.on("back", function() {
	do_App.closePage();
});
// 左上角-返回
var headerLeft = ui(addheader + ".headerLeft");
// 右上角-
var headerRight = ui(addheader + ".headerRight");
var labelNext = ui(addheader + ".labelNext");
labelNext.visible = true;
headerLeft.on("touch", function() {
	do_App.closePage()
});
var header = ui("header");
var imgMax = 9;
header.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "创建活动",
	"labelNext" : "发布"
})
header.refreshData();
/** **************处理-图片显示UI-end**************** */
var aLayoutLogo = ui("aLayoutLogo");
var imageViewLogo=ui("imageViewLogo");
//更换logo
aLayoutLogo.on("touch", function() {
	imgTool.banCut(selectImgBack2);// /选择图片并裁剪
});
var logo;
function selectImgBack2(imgList) {
	//do_App.openPage("source://view/public/imgselect/crop.ui",{"imgSource":imgList[0],"cropArea":"640,250"});
	do_App.openPage("source://view/public/imgselect/crop.ui",{"imgSource":imgList[0],"cropArea":"640,250"});
}
var circleName;
//页面装载完成后，开始初始化工作
do_Page.on("loaded", function(){
	//读取当前页面的传入参数
	var data=do_Page.getData();
	bizzId=data.circleId;
	circleName=data.circleName;
	labelTypeText.text=circleName;
});
var aLayoutImg = ui("aLayoutImg");

var imgGridView = ui("imgGridView");
var imgsData = []; //保存图片数组
imgGridView.on("touch", function(data, e) {
	imgMax=imgMax+1;
	imgsData.splice(data,1);
	imgGridView.items = imgsData;
});
/** **************处理-图片显示UI-end**************** */

/** **************点击-添加图片-begin**************** */
aLayoutImg.on("touch", function(data, e) {
	if (0== imgMax) {
		return;
	}
	imgTool.imgMulti(imgMax, selectImgBack);// 选择多张图片
});

function selectImgBack(imgList) {
	imgMax=imgMax-imgList.length;
	imgsData = imgsData.concat(imgList.map(function(path) {
		return {
			"imgPath" : path
		}
	}));
	imgGridView.items = imgsData;
}
/** **************点击-添加图片-end**************** */
var layout_main=ui("do_LinearLayout_main");

var textBoxContent = ui("textBoxContent");

//设置活动名称
var nameTextInput=ui("do_TextField_1");

/**
 * 简介之后的内容
 */
var layoutForm=ui("layoutForm");
var addPicker = aLayoutRoot.add("picker",
		"source://view/reuse/form/oneCategory.ui", 0, 0);
/**
 * 变量
 */
var dingweiX,dingweiY,bizzId;
var startTime,endTime,signEndTime;
//设置报名截止时间
var addSignEndAt = layoutForm.add("signEndAt",
		"source://view/reuse/form/mutiLabel.ui", 0, 0);
var signEndAt = ui("signEndAt");
signEndAt.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "报名截止时间",
	"labelText" : '',
	"labelTipsVisible" : false,
	"inputType":"ASC",
	"imgForward":"source://image/common/forward.png"
});
signEndAt.refreshData();

var labelSignEndAt = ui(addSignEndAt + ".labelText");
ui(addSignEndAt + ".labelAout").on("touch",function() {
	do_Page.hideKeyboard();
	do_DateTimePicker.show({type:0, data:date0, maxDate:"",minDate:date0, title:"报名截止时间", buttons:["取消","确定"]}, function(data, e){
        if(data.flag==1){
        	signEndTime=parseInt(data.time,10);
        	if(signEndTime>endTime){
        		nf.toast("亲，报名截止时间必须小于活动结束时间。")
        		return;
        	}
        	labelSignEndAt.text=timeFormat(signEndTime);
        	
        }
    });
});


/*
 * ****报名限制
 */
var labelTypeId = 2;
//限制选项
var addLabelType = layoutForm.add("labelType",
		"source://view/reuse/form/mutiLabel.ui", 0, 0);
var labelType = ui("labelType");
hashdata.addData({
	"labelTitle" : "圈子",
	"labelText" : '',
	"labelTipsVisible" : false,
	"inputType":"ASC",
	"imgForward":"source://image/common/forward.png"
});
labelType.bindData(hashdata);
labelType.refreshData();
labelType.visible=true;
var labelTypeText=ui(addLabelType+".labelText");

ui(addLabelType + ".labelAout").on("touch", function() {
	if(labelTypeId==1){
			helperOpen.open("source://view/community/select/selectRadio.ui",{'bizzId':bizzId});
	}else if(labelTypeId==2){
		helperOpen.open("source://view/circle/select/selectRadio.ui",{'bizzId':bizzId,"forWhat":"addCircleActivity"});
	}
})


var addActivityType = layoutForm.add("activityType",
		"source://view/reuse/form/mutiLabel.ui", 0, 0);
var activityType = ui("activityType");
activityType.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "报名限制",
	"labelText" : '',
	"labelTipsVisible" : false,
	"inputType":"ASC",
	"imgForward":"source://image/common/forward.png"
});
activityType.refreshData();
var labelTypeName = ui(addActivityType + ".labelText");
labelTypeName.text="圈子";

	
ui(addActivityType + ".labelAout").on("touch", function() {
	do_Page.hideKeyboard();
	var param = {}
	var ptitle = {
		"title" : "报名限制",
		"id" : "tId"
	}
	var datas = [ {
		id : "2",
		name : "圈子"
	}];
	var pcount = [ ptitle, datas ];
	do_Page.fire("oneCategoryList", pcount);
	do_Page.fire("oneCategory", "true");
});

/*
 * **** 费用类型
 */
//设置价格
var addPriceInput = layoutForm.add("priceInput",
		"source://view/reuse/form/mutiInput.ui", 0, 0);
var priceInput = ui("priceInput");
hashdata.addData({
	"textTitle" : 'AA价格',
	"inputType":"PHONENUMBER",
	"hint" : '价格'
});
priceInput.bindData(hashdata);
priceInput.refreshData();
priceInput.visible=false;
var textInput=ui(addPriceInput+".textInput");

var labelCostId = 1;
var addCostType = layoutForm.add("costType",
		"source://view/reuse/form/mutiLabel.ui", 0, 0);
var costType = ui("costType");
costType.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "费用类型",
	"labelText" : '',
	"labelTipsVisible" : false,
	"imgForward":"source://image/common/forward.png"
});
costType.refreshData();
var labelCostName = ui(addCostType + ".labelText");
labelCostName.text="现场支付";
ui(addCostType + ".labelAout").on("touch", function() {
	do_Page.hideKeyboard();
	var param = {}
	var ptitle = {
		"title" : "费用类型",
		"id" : "cId"
	}
	var datas = [{
		id : "1",
		name : "现场支付"
	}, {
		id : "2",
		name : "免费"
	},{
		id : "3",
		name : "AA制"
	}];
	var pcount = [ ptitle, datas ];
	do_Page.fire("oneCategoryList", pcount);
	do_Page.fire("oneCategory", "true");
});
do_Page.on("refreshOneCategory", function(data) {
	if ("cId" == data[1]) {
		labelCostName.text = data[0].onename;
		labelCostId = data[0].oneid;
		if(labelCostId==3){//显示出价格
			priceInput.visible=true;
			layoutForm.redraw();
		}else{
			textInput.text="";
			priceInput.visible=false;
			layoutForm.redraw();
		}
	}else if("tId" == data[1]){
		labelTypeName.text = data[0].onename;
		labelTypeId = data[0].oneid;
		bizzId=null;
		hashdata.addData({
			"labelTitle" : labelTypeName.text+"范围",
			"labelText" : '',
			"labelTipsVisible" : false,
			"imgForward":"source://image/common/forward.png"
		});
		labelType.bindData(hashdata);
		labelType.refreshData();
	}
});


//设置活动地址
var addAddressLable = layoutForm.add("addressLable",
		"source://view/reuse/form/mutiInput2.ui", 0, 0);
var addressLable = ui("addressLable");
hashdata.addData({
	"textTitle" : '地点',
	"imgForward":"source://image/menu/near.png",
	"inputType":"ASC",
	"hint":""
});
addressLable.bindData(hashdata);
addressLable.refreshData();
var addressLabelText=ui(addAddressLable+".textInput");
ui(addAddressLable + ".leftAlayout").on("touch",function() {
	helperOpen.open("source://view/area/map.ui");
});
/**
 * 时间add
 */

//设置结束时间
var addEndAt = layoutForm.add("endAt",
		"source://view/reuse/form/mutiLabel.ui", 0, 0);
var endAt = ui("endAt");
endAt.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "结束时间",
	"labelText" : '',
	"inputType":"ASC",
	"labelTipsVisible" : false,
	"imgForward":"source://image/common/forward.png"
});
endAt.refreshData();

var labelEndAt = ui(addEndAt + ".labelText");
ui(addEndAt + ".labelAout").on("touch",function() {
	do_Page.hideKeyboard();
	do_DateTimePicker.show({type:0, data:date0, maxDate:"",minDate:date0, title:"结束时间", buttons:["取消","确定"]}, function(data, e){
        if(data.flag==1){
        	endTime=parseInt(data.time,10);
        	if(endTime<startTime){
        		nf.toast("亲，活动结束时间必须大于开始时间。")
        		return;
        	}
        	labelEndAt.text=timeFormat(endTime);
        	
        }
    });
});

//设置开始时间
var addStartAt = layoutForm.add("startAt",
		"source://view/reuse/form/mutiLabel.ui", 0, 0);
var startAt = ui("startAt");
startAt.bindData(hashdata);
hashdata.addData({
	"labelTitle" : "开始时间",
	"labelText" : '',
	"inputType":"ASC",
	"labelTipsVisible" : false,
	"imgForward":"source://image/common/forward.png"
});
startAt.refreshData();

var labelStartAt = ui(addStartAt + ".labelText");
ui(addStartAt + ".labelAout").on("touch",function() {
	do_Page.hideKeyboard();
	do_DateTimePicker.show({type:0, data:date0, maxDate:"",minDate:date0, title:"开始时间", buttons:["取消","确定"]}, function(data, e){
        if(data.flag==1){
        	startTime=parseInt(data.time,10);
        	labelStartAt.text=timeFormat(startTime);
        	
        }
    });
});

function timeFormat(time){
	var svDate = new Date(time);//要格式化的时间
	var minutes=0;
	if(svDate.getMinutes()<10){
		minutes="0"+svDate.getMinutes();
	}else{
		minutes=svDate.getMinutes();
	}
	var hours=0;
	if(svDate.getHours()<10){
		hours="0"+svDate.getHours();
	}else{
		hours=svDate.getHours();
	}
	return svDate.getFullYear()+"/"+(svDate.getMonth()+1)+"/"+svDate.getDate()+' '+hours+':'+minutes;
}
//从新增页面返回,刷新数据
do_Page.on("result", function(data) {
	if(null!=data.longitude){
		dingweiX = data.longitude;
		dingweiY = data.latitude;
		if(null!=data.address){
			addressLabelText.text=data.address;
		}
	}
	if (null!=data&&data.pageFrom=="imgCrop"){
		logo=data.imgCrop;
		imageViewLogo.source=data.imgCrop;
	}
	if(null!=data.type){
		bizzId=data.id;
		labelTypeText.text=data.name;
	}
});
ui("do_ScrollView_1").redraw();
headerRight.on("touch", "", 5000, function() {
	create();
})
function create() {
	do_Page.hideKeyboard();
	if (nameTextInput.text == '' || nameTextInput.text == null) {
		nf.toast("亲，请输入活动名称。");
		return;
	}
	if (logo == '' || logo == null) {
		nf.toast("亲，请上传活动海报。");
		return;
	}
	if (textBoxContent.text == '' || textBoxContent.text == null) {
		nf.toast("亲，请填写活动简介。");
		return;
	}
	if (imgsData.length == 0) {
		nf.toast("亲，请添加活动简介图片。");
		return;
	}
	if (startTime<=0 || startTime == null) {
		nf.toast("亲，请选择活动开始时间。");
		return;
	}
	if (endTime<=0 || endTime == null) {
		nf.toast("亲，请选择活动结束时间。");
		return;
	}
	if(endTime<startTime){
		nf.toast("亲，活动结束时间必须大于活动开始时间。");
		return;
	}
	if (dingweiX=='' || dingweiX == null) {
		nf.toast("亲，请定位地址。");
		return;
	}
	if (labelCostId==3) {
		if(textInput.text==null ||textInput.text== ''){
			nf.toast("亲，请填写AA制的价格。");
			return;
		}
	}
	if (bizzId=='' || bizzId == null) {
		nf.toast("亲，请选择范围。");
		return;
	}
	if (signEndTime<=0 || signEndTime == null) {
		nf.toast("亲，请选择活动报名截止时间。");
		return;
	}
	if(endTime<signEndTime){
		nf.toast("亲，报名截止时间必须小于活动结束时间。");
		return;
	}
	
	var imgFiles = [];
	imgFiles.push(logo);
	for (var i = 0; i < imgsData.length; i++) {
		imgFiles.push(imgsData[i].imgPath);
	}
	if (imgFiles.length > 0) {
		qqHttp.form(imgFiles, "activity", function(imgDatas) {
			var string4imgs = imgDatas.path;// 返回图片云端路径（后部份）用分号隔开
			var imgs=string4imgs.split(";");
			var imgFiles2 = [];
			for (var i = 0; i < imgs.length; i++) {
				if(i==0){
					logo=imgs[i];
				}else{
					imgFiles2.push(imgs[i]);
				}
			}
			var params = {
				"type" : labelTypeId,
				"bizzId" : bizzId,
				"name" : nameTextInput.text,
				"resume" : textBoxContent.text,
				"resumeImg" : imgFiles2.join(";"),
				"logo" : logo,
				"address" : addressLabelText.text,
				"x" : dingweiX,
				"y" : dingweiY,
				"costType":labelCostId,
				"cost":textInput.text,
				"signEndAt":signEndTime,
				"startAt":startTime,
				"endAt":endTime,
			};
			qqHttp.post(activityCreateUrl, params, function(data) {
				nf.toast("发布成功");
				do_App.closePage({fromPage:'activity_add'});
			})
		});
	} 
}

//点击背景隐藏输入键盘
root.on("touch",function(){
	do_Page.hideKeyboard();
})